package com.hex.es.service.impl;

import com.hex.es.annotation.EsBuildParamTypeInfo;
import com.hex.es.aop.AbstractEsAop;
import com.hex.es.service.ParamBuildInterface;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * @description: 普通查询参数构建器
 * @author: Hex
 * @date: 2019/11/20 16:29
 */
@Slf4j
@Service
public class ParamBuildBaseImpl extends AbstractEsAop implements ParamBuildInterface {

    @Override
    public void paramBuild(Object key, Object value, BoolQueryBuilder boolQueryBuilder, NativeSearchQueryBuilder searchQueryBuilder, EsBuildParamTypeInfo esBuildParamTypeInfo) {
        if (!key.equals(esBuildParamTypeInfo.rowOffsetFieldName()) &&
                !key.equals(esBuildParamTypeInfo.pageSizeFieldName()) &&
                !Arrays.asList(esBuildParamTypeInfo.fromFieldName()).contains(key.toString()) &&
                !Arrays.asList(esBuildParamTypeInfo.toFieldName()).contains(key.toString()) &&
                value != null &&
                StringUtils.isNotEmpty(value.toString())) {
            for (String shouldFieldName : esBuildParamTypeInfo.shouldField()) {
                if (key.toString().equals(shouldFieldName)) {
                    boolQueryBuilder.should(QueryBuilders.matchQuery(humpToUnderline(key.toString()), value));
                    return;
                }
            }
            boolQueryBuilder.must(QueryBuilders.matchQuery(humpToUnderline(key.toString()), value));
        }
    }
}
